/**
 * @name: findSiblingIds
 * @description: 获取传入id的兄弟节点
 * @param {Array} list //树形机构数据
 * @param {String} id //需要查找的id
 * @return {Array} //返回兄弟节点
 */
function findSiblingIds(list, id) {
  let node;
  for (let i in list) {
    if (list[i].id === id) {
      return list.filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = findSiblingIds(list[i].children, id);
      if (node) return node.filter((v) => v.id !== id);
    }
  }
  return node;
}

function addStationName(list) {
  list.forEach((item) => {
    if (item.level == 1) {
      item.label = item.orgName;
      item.id = item.orgId;
    }
    if (item.level == 2) {
      item.label = item.stationName;
      item.id = item.stationId;
    }
    if (item.level == 3) {
      item.label = item.unitsName;
      item.id = item.unitsId;
    }

    if (item.children) {
      addStationName(item.children);
    }
  });
  return list;
}

// 传入一个id获取它父级的id
function getAllParentNodes(list, id) {
  if (list.length === 0 || !list) return [];
  let node;

  for (let i in list) {
    if (list[i].id === id) {
      return [list[i]].filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = getAllParentNodes(list[i].children, id);
      if (node) return node.concat(list[i]).filter((v) => v.id !== id);
    }
  }
  return node;
}

function msgFn(deviceid, imgSource, width, height) {
  return JSON.stringify({
    func: "showImageOnDevices",
    param0: deviceid,
    param1: imgSource,
    param2: width,
    param3: height,
  });
}
let deviceList = [
  {
    id: "3800756696423979041",
    name: "新西线16903开关",
    gh: "100kW",
    rl: "4000kWh",
  },
  {
    id: "3800756696423979049",
    name: "新西线16903开关",
    gh: "1000kW",
    rl: "2000kWh",
  },
  {
    id: "3800756696423979182",
    name: "新西线16903开关",
    gh: "500kW",
    rl: "1000kWh",
  },
];

import { Message } from "element-ui";
import {
  queryStationFileList,
  updateStationInfoFile,
  queryStationTestNumber,
} from "@/api/windPower.js";
import {
  adjustRegulationList,
  regulationOrgList,
  stationTypeList,
  voltageLevelList,
  queryUnitsNameList,
  queryStationNameList,
  queryOfExperimentalresults,
  updateStationFileWarn,
} from "@/api/dict.js";
import TestResultEdit from "@/views/testResult/testResultEdit/testResultEdit.vue";
import { queryTableList } from "@/api/UsageAnalysis.js";
import { queryTreeData } from "@/api/common.js";
import { tableDataAll } from "./data";

export default {
  components: { TestResultEdit },
  name: "maintenanceRecord",
  data() {
    return {
      queryStationFileList,
      queryStationNameList,
      queryUnitsNameList,
      queryTableList,
      formData: new FormData(),
      excelData: [],
      columns: [],
      getFrom: {}, //每行的数据
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      adjustRegulationLists: [], //上下调投入分类下拉框的数据
      voltageLevelLists: [], //电压等级下拉框的数据
      addDialogVisibleTitle: "新增",
      id: 0,
      dataTree: [],
      currentLivingId: "",
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      defaultProps: {
        children: "feeders",
        label: "name",
      },
      queryDetailParam: {
        regulationOrgIds: [],
        stationIds: [],
        fileSort: "01",
        testDate: "",
        testNumber: "",
        isAudited: 1,
      },
      operate: "add",
      testNumberList: [], //测试序号
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      headList: [
        {
          name: "编号",
          value: "planningName",
          noSort: true,
        },
        {
          name: "首端连接点号",
          value: "stationName",
          noSort: true,
        },
        {
          name: "末端连接点号",
          value: "planningName",
          noSort: true,
        },
        {
          name: "有功功率(kW)",
          value: "planningName",
          noSort: true,
        },
        {
          name: "无功功率(kvar)",
          value: "planningName",
          noSort: true,
        },
        {
          name: "电压(V)",
          value: "planningName",
          noSort: true,
        },
        {
          name: "电流(A)",
          value: "planningName",
          noSort: true,
        },
      ],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "80px",
      // 预览弹框f
      dialogPreVisible: false,
      paramData: [],
      checkList: [],
      checkId: "",
      queryParamStationId: "",
      showXLSX: false,
      xData: [
        "4.1",
        "4.2",
        "4.3",
        "4.4",
        "4.5",
        "4.6",
        "4.7",
        "4.8",
        "4.9",
        "4.10",
        "4.11",
        "4.12",
      ],
      dxtUrl:
        "http://pdyzz.test.com.cn/graph/Navigator.html?graph=新西169线单线图.sln.pic.g",
      // 树节点相关
      allIds: [],
      defaultExpandedNode: [],
      currentKey: "",

      // 变电站下拉列表
      stationOptions: [
        {
          value: "001",
          label: "变电站1",
        },
        {
          value: "002",
          label: "变电站2",
        },
      ],
      // 馈线下拉列表
      lineOptions: [
        {
          value: "001",
          label: "变电站1",
        },
        {
          value: "002",
          label: "变电站2",
        },
      ],
      upForm: {
        // 缓存状态类型
        statusType: "1",
      },

      // 缓存状态类型列表
      statusTypeOptions: [
        {
          value: "1",
          label: "倒送状态",
        },
        {
          value: "2",
          label: "高负载状态",
        },
        {
          value: "3",
          label: "冬季典型状态",
        },
        {
          value: "4",
          label: "夏季典型状态",
        },
        {
          value: "5",
          label: "春秋典型状态",
        },
      ],
      bottomForm: {
        // 变电站id
        date: this.dateFormat(new Date().getTime()),
      },
      filterText: "",
      tableDataAll: tableDataAll,
      tableData: [],

      isBubble: false,
    };
  },

  mounted() {
    this.getTreeFn();
  },
  created() {
    // this.regulationOrgList()
    // this.stationTypeList()
    // this.adjustRegulationList()
    // this.voltageLevelList()
    // this.getTreeData()
    // this.queryStationTestNumber()
    this.tableData = this.tableDataAll.filter((item) => item.type == "1");
  },
  methods: {
    dateFormat(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();

      return year + "-" + month + "-" + day;
    },

    // 获取渲染树的数据
    getTreeData(data) {},
    // 下拉框change事件
    inputChange(val) {
      // console.log(val, "搜索下拉框val");
      // console.log(this.$refs.equipmentTree.queryInputListCopy, "搜索下拉框val");
      let param = {
        stationId: val,
      };
      this.getTreeData(param);
    },
    // 点击树的勾选框
    handleCheck(checkedKeys, e) {
      if (this.queryParamStationId !== "") {
        console.log("有查询条件");
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "01",
        };

        if (e.checkedKeys[1]) {
          params.stationIds.push(e.checkedKeys[1]);
        }
        this.queryDetailParam = params;
      } else {
        console.log("无查询条件");
        let nodeList = this.$refs.equipmentTree.getCheckedNodes();
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "01",
        };
        nodeList
          .filter((e) => e.level !== "3")
          .forEach((item) => {
            if (item.level === "1") {
              params.regulationOrgIds.push(item.id);
            }
            if (item.level === "2") {
              params.stationIds.push(item.id);
            }
          });
        this.queryDetailParam = params;
        params.stationIds.forEach((e, i) => {
          if (
            params.regulationOrgIds.includes(
              getAllParentNodes(this.dataTree, e)[0].id
            )
          ) {
            // 找到这个元素删掉他
            this.queryDetailParam.stationIds =
              this.queryDetailParam.stationIds.filter((d) => d !== e);
          }
        });
      }
      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
      });
    },
    // 处理三级节点之间勾选联动
    checkChange(row, col, check) {
      //console.log(this.dataTree, "this.dataTree");
      if (row.level == "3") {
        // console.log(row, col, check, "row, col");
        let checkedKeys = findSiblingIds(this.dataTree, row.id);
        // console.log(checkedKeys,'checkedKeyscheckedKeys')
        checkedKeys.forEach((item) => {
          this.$refs.equipmentTree.setChecked(item.id, col);
        });
      }
    },

    // 总调下拉框的数据
    async regulationOrgList() {
      await regulationOrgList().then((res) => {
        if (res.code === "000000") {
          this.dispatchList = res.data;
        }
      });
    },

    // 上下调投入分类下拉框的数据
    async adjustRegulationList() {
      await adjustRegulationList().then((res) => {
        if (res.code === "000000") {
          this.adjustRegulationLists = res.data;
        }
      });
    },
    // 场站类型下拉框的数据
    async stationTypeList() {
      await stationTypeList().then((res) => {
        if (res.code === "000000") {
          this.stationTypeLists = res.data;
        }
      });
    },
    // 电压等级下拉框的数据
    async voltageLevelList() {
      await voltageLevelList().then((res) => {
        if (res.code === "000000") {
          this.voltageLevelLists = res.data;
        }
      });
    },

    // 测试序号下拉
    async queryStationTestNumber() {
      await queryStationTestNumber(this.queryDetailParam).then((res) => {
        if (res.code === "000000") {
          this.testNumberList = res.data;
        }
      });
    },

    // 测试日期
    testDateChange(val) {
      if (val) {
        this.$set(this.queryDetailParam, "testNumber", "");
        this.queryStationTestNumber();
      }
    },
    // 新增弹框
    addWindPower() {
      this.id++;
      // this.operate === "add";
      this.$set(this, "operate", "add");
      this.dialogFormVisible = true;
      this.addDialogVisibleTitle = "新增";
      this.getFrom = { regulationOrgId: "1", caseIsAudited: "" };
      console.log(this.getFrom);
    },

    // 获取表格多行选中的数据  点击行选中
    getMultipleSelection2(row) {
      this.tableData = JSON.parse(JSON.stringify(row));
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    getMultipleSelection() {
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.windPowerTable.multipleSelection)
      );
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    // 编辑
    editWindPower(row) {
      console.log(row);
      if (row) {
        this.$set(this, "operate", "edit");
        this.getMultipleSelection2([row]);
        this.dialogFormVisible = true;
        this.addDialogVisibleTitle = "修正";
        return true;
      } else {
        this.operate = "edit";
        this.getMultipleSelection();
        if (this.tableData && this.tableData.length < 1) {
          Message.warning("请先勾选要编辑的数据");
        } else if (this.tableData && this.tableData.length > 1) {
          Message.warning("编辑的时候只能选择一条数据,请重新选择");
          return false;
        } else {
          this.addDialogVisibleTitle = "修正";
          this.dialogFormVisible = true;
          // this.$nextTick(()=>{
          // this.$refs.childRules.$refs.stationRefEdit.value=this.getFrom.stationName
          // })
          return true;
        }
      }
    },

    // 检索
    searchList() {
      return;
      this.$refs.windPowerTable.getDataInit();
    },

    handleClear() {
      this.getTreeData();
    },

    // 给树节点添加唯一标识
    dataTreeFn(data) {
      for (const item of data) {
        if (item.feeders) {
          item.id = item.substationId;
          this.dataTreeFn(item.feeders);
        } else {
          item.id = item.feederId;
          this.allIds.push(item.feederId);
        }
      }
    },

    // 获取树结构
    async getTreeFn() {
      let params = {
        substationId: "",
      };
      let { resultCode, data } = await queryTreeData(params);
      if (resultCode == 0) {
        this.$nextTick(() => {
          this.dataTree = data;
          this.dataTreeFn(data);
          // 默认展开第一条
          this.defaultExpandedNode.push(this.allIds[0]);
          if (this.dataTree.length && this.dataTree[0].feeders.length) {
            this.currentFeederId = this.allIds[0];
            this.queryDetailParam.feederId = this.allIds[0];
            this.expandDefault();
            this.searchList();
          }
        });
      }
    },

    // 默认展开第一条
    expandDefault() {
      this.$nextTick(() => {
        this.$refs.equipmentTree.setCurrentKey(this.allIds[0]);
      });
    },

    // 单击节点
    handleNodeClick(data) {
      if (data.feederId) {
        this.currentFeederId = data.feederId;
        this.queryDetailParam.feederId = this.currentFeederId;
        // this.searchList();
      }
    },
    // 树搜索
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    //
    changeStatusFn(val) {
      if (val === "") {
        this.tableData = this.tableDataAll;
        return;
      }
      this.tableData = this.tableDataAll.filter((item) => item.type == val);
    },
  },
};
